<template>
  <div class="app-container">
    <div class="super-flow-base-demo">
      <el-button
      v-if="$route.fullPath.indexOf('workflowMGMT') > -1"
      style="position: absolute; top: 20px; right: 20px; z-index: 100"
      type="primary"
      @click="handleSave()"
      >保存</el-button
    >
      <super-flow
        ref="superFlow"
        :relation-mark="relationMark"
        :start-mark="startMark"
        :end-mark="endMark"
        :node-list="nodeList"
        :link-list="linkList"
        :origin="origin"
        :graph-menu="graphMenuList"
        :node-menu="nodeMenuList"
        :link-menu="linkMenuList"
        :enter-intercept="enterIntercept"
        :output-intercept="outputIntercept"
        :link-desc="linkDesc"
        :link-style="linkStyle"
      >
        <template v-slot:node="{ meta, node }">
          <div :class="`flow-node flow-node-${meta.prop}`">
            <header>
              {{ meta.nodeName }}
            </header>
            <section v-if="meta.prop != 'end'">
              {{ meta.description }}
            </section>
          </div>
        </template>
      </super-flow>
    </div>
    <div class="formcontent">
      <template v-if="currentEdit == 'node'">
        <h1 style="text-align: center">节点属性{{currentType=='edit'?'编辑':'展示'}}</h1>
        <!-- <form action="">
          <div class="formitem">
            <span class="formitem-title">节点名称：</span
            ><input type="text" v-model="form.name" />
          </div>
          <div class="formitem">
            <span class="formitem-title">节点描述：</span
            ><input type="text" v-model="form.desc" />
          </div>
          <div class="formitem">
            <span class="formitem-title">节点属性：</span><input type="text" />
          </div>
          <div class="formitem">
            <span class="formitem-title">角色：</span><input type="text" />
          </div>
          <div class="formitem">
            <span class="formitem-title">人员：</span><input type="text" />
          </div>
          <div class="formitem"></div>
          <div class="formitem">
            <span class="formitem-title">执行脚本：</span><input type="text" />
          </div>
          <div class="formitem">
            <span class="formitem-title">是否拒绝到开始节点：</span
            ><input type="text" />
          </div>
          <div class="formitem">
            <span class="formitem-title">拒绝到开始处理程序：</span
            ><input type="text" />
          </div>
          <div class="formitem">
            <span class="formitem-title">是否是自动节点：</span
            ><input type="text" />
          </div>
          <div class="formitem">
            <span class="formitem-title">是否回收：</span><input type="text" />
          </div>
          <div class="formitem">
            <span class="formitem-title">是否委托：</span><input type="text" />
          </div>
        </form> -->
        <el-col
          class="flex"
          v-for="(formItem, index) in showNodeFormData"
          :key="index"
        >
          <template v-if="index % 2 == 0">
            <span class="extendedMain fromTitle"> {{ formItem.name }}： </span>
            <div class="extendedMain content">
              <dynamic-form-Item
                :addform="[formItem]"
                :form="form"
                :disabled="currentType=='show'"
              ></dynamic-form-Item>
            </div>
            <template v-if="index != showNodeFormData.length - 1">
              <span class="extendedMain fromTitle">
                {{ showNodeFormData[index + 1].name }}：
              </span>
              <div class="extendedMain content">
                <dynamic-form-Item
                  :addform="[showNodeFormData[index + 1]]"
                  :form="form"
                  :disabled="currentType=='show'"
                ></dynamic-form-Item>
              </div>
            </template>
            <template v-if="index == showNodeFormData.length - 1">
              <span class="extendedMain fromTitle"></span>
              <span class="extendedMain content"></span>
            </template>
          </template>
        </el-col>
      </template>
      <template v-if="currentEdit == 'link'">
        <h1 style="text-align: center">路径属性编辑</h1>
        <el-col
          class="flex"
        >
          <span class="extendedMain fromTitle"> from节点名称：</span>
          <div class="extendedMain content">
            <el-input type="text" v-model="form.fromName" disabled/>
          </div>
          <span class="extendedMain fromTitle"> from节点描述：</span>
          <div class="extendedMain content">
            <el-input type="text" v-model="form.fromDescription" disabled/>
          </div>
        </el-col>
        <el-col
          class="flex"
        >
          <span class="extendedMain fromTitle"> to节点名称：</span>
          <div class="extendedMain content">
            <el-input type="text" v-model="form.toName" disabled/>
          </div>
          <span class="extendedMain fromTitle"> to节点描述：</span>
          <div class="extendedMain content">
            <el-input type="text" v-model="form.toDescription" disabled/>
          </div>
        </el-col>
        <el-col
          class="flex"
        >
          <span class="extendedMain fromTitle"> 路径标识：</span>
          <div class="extendedMain content">
            <el-input type="text" v-model="form.roadFlag"/>
          </div>
          <span class="extendedMain fromTitle"> 执行脚本：</span>
          <div class="extendedMain content">
            <el-input type="text" v-model="form.fromDescription"/>
          </div>
        </el-col>
        <el-col
          class="flex"
        >
          <span class="extendedMain fromTitle"> 路径类型：</span>
          <div class="extendedMain content">
            <el-select v-model="form.operationType" style="width: 170.2px">
              <el-option value="Reject">拒绝</el-option>
              <el-option value="Approve">审批</el-option>
            </el-select>
          </div>
        </el-col>
        <el-col
          class="flex"
          v-if="form.operationType != 'Reject'"
        >
          <span class="extendedMain fromTitle"> 路径属性：</span>
          <div class="extendedMain content">
            <el-input type="text" v-model="form.fromDescription" disabled/>
          </div>
          <span class="extendedMain fromTitle"> 是否是自动路径：</span>
          <div class="extendedMain content">
              <el-radio-group
                v-model="form.roadAuto"
              >
                <el-radio
                  label="1"
                  >是
                </el-radio>
                <el-radio
                  label="0"
                  >否
                </el-radio>
              </el-radio-group>
          </div>
        </el-col>
        <!-- <form action="" v-model="form">
          <div class="formitem">
            <span class="formitem-title">from节点名称：</span
            ><input type="text" v-model="form.fromName" disabled/>
          </div>
          <div class="formitem">
            <span class="formitem-title">from节点描述：</span
            ><input type="text" v-model="form.fromDescription" disabled/>
          </div>
          <div class="formitem">
            <span class="formitem-title">to节点名称：</span
            ><input type="text" v-model="form.toName" disabled/>
          </div>
          <div class="formitem">
            <span class="formitem-title">to节点描述：</span
            ><input type="text" v-model="form.toDescription" disabled/>
          </div>
          <div class="formitem">
            <span class="formitem-title">路径标识：</span
            ><input type="text" v-model="form.roadFlag" />
          </div>
          <div class="formitem" v-if="form.operationType != 'Reject'">
            <span class="formitem-title">路径属性：</span><input type="text" />
          </div>
          <div class="formitem">
            <span class="formitem-title">执行脚本：</span><input type="text" />
          </div>
          <div class="formitem" v-if="form.operationType != 'Reject'">
            <span class="formitem-title">是否是自动路径：</span
            >
              <el-radio-group
                v-model="form.roadAuto"
              >
                <el-radio
                  label="1"
                  >是
                </el-radio>
                <el-radio
                  label="0"
                  >否
                </el-radio>
              </el-radio-group>
          </div>
          <div class="formitem">
            <span class="formitem-title">路径类型：</span
            ><select v-model="form.operationType" style="width: 170.2px">
              <option value="Reject">拒绝</option>
              <option value="Approve">审批</option>
            </select>
          </div>
        </form> -->
      </template>
    </div>
  </div>
</template>
<script>
import request from "@/utils/request";
const relationMark = "id";
const startMark = "fromid";
const endMark = "toid";
const drawerType = {
  node: 0,
  link: 1,
};
// /pms/workflow/nodeFlowChartList?workflowid=1849728278970368
// /pms/pageConfig/getAddForm?addForm=add_node
export default {
  components: {
    SuperFlow: () => import("./packages/index.vue"),
    dynamicFormItem: () => import("@/views/components/dynamicFormItem"),
  },
  data() {
    return {
      drawerType,
      relationMark,
      startMark,
      endMark,
      drawerConf: {
        title: "",
        visible: false,
        type: null,
        info: null,
        open: (type, info) => {
          const conf = this.drawerConf;
          conf.visible = true;
          conf.type = type;
          conf.info = info;
          if (conf.type === drawerType.node) {
            conf.title = "节点";
            if (this.$refs.nodeSetting) this.$refs.nodeSetting.resetFields();
            this.$set(this.nodeSetting, "name", info.meta.name);
            this.$set(this.nodeSetting, "desc", info.meta.desc);
          } else {
            conf.title = "连线";
            if (this.$refs.linkSetting) this.$refs.linkSetting.resetFields();
            this.$set(
              this.linkSetting,
              "desc",
              info.meta ? info.meta.desc : ""
            );
          }
        },
        cancel: () => {
          this.drawerConf.visible = false;
          if (this.drawerConf.type === drawerType.node) {
            this.$refs.nodeSetting.clearValidate();
          } else {
            this.$refs.linkSetting.clearValidate();
          }
        },
      },
      linkSetting: {
        desc: "",
        resetFields: () => null,
      },
      nodeSetting: {
        name: "",
        desc: "",
        clearValidate: () => null,
      },
      origin: [50, 50],
      nodeList: [],
      linkList: [],

      graphMenuList: [
        [
          {
            label: "开始节点",
            disable(graph) {
              return !!graph.nodeList.find(
                (node) => node.meta.prop === "start"
              );
            },
            selected: (graph, coordinate) => {
              request({url:'/pms/workflowMGMT/nextvalId'}).then(res=>{
                graph.addNode({
                  id: res.data.id,
                  width: 120,
                  height: 60,
                  coordinate: coordinate,
                  meta: {
                    id: res.data.id,
                    prop: "start",
                    nodeName: "开始节点",
                  },
                });
              })
            },
          },
          //   {
          //     label: "条件节点",
          //     disable: false,
          //     selected: (graph, coordinate) => {
          //       graph.addNode({
          //         width: 120,
          //         height: 60,
          //         coordinate: coordinate,
          //         meta: {
          //           prop: "condition",
          //           name: "条件节点",
          //         },
          //       });
          //     },
          //   },
          //   {
          //     label: "节点",
          //     disable: false,
          //     selected: (graph, coordinate) => {
          //       graph.addNode({
          //         width: 120,
          //         height: 60,
          //         coordinate: coordinate,
          //         meta: {
          //           prop: "approval",
          //           name: "节点",
          //         },
          //       });
          //     },
          //   },
          {
            label: "审批节点",
            disable: false,
            selected: (graph, coordinate) => {
              request({url:'/pms/workflowMGMT/nextvalId'}).then(res=>{
                graph.addNode({
                  id: res.data.id,
                  width: 120,
                  height: 60,
                  coordinate: coordinate,
                  meta: {
                    id: res.data.id,
                    prop: "cc",
                    nodeName: "审批节点",
                  },
                });
              })
            },
          },
          {
            label: "结束节点",
            disable(graph) {
              return !!graph.nodeList.find(
                (point) => point.meta.prop === "end"
              );
            },
            selected: (graph, coordinate) => {
              request({url:'/pms/workflowMGMT/nextvalId'}).then(res=>{
                graph.addNode({
                  id: res.data.id,
                  width: 80,
                  height: 60,
                  coordinate: coordinate,
                  meta: {
                    id: res.data.id,
                    prop: "end",
                    nodeName: "结束节点",
                  },
                });
              })
            },
          },
        ],
        [
          {
            label: "打印数据",
            selected: (graph, coordinate) => {
              console.log(JSON.stringify(graph.toJSON(), null, 2));
            },
          },
          {
            label: "全选",
            selected: (graph, coordinate) => {
              graph.selectAll();
            },
          },
        ],
      ],
      nodeMenuList: [
        [
          {
            label: "删除",
            disable() {
              return this.edit;
            },
            selected(node, coordinate) {
              node.remove();
            },
          },
        ],
        [
          {
            label: "编辑",
            disable() {
              return this.edit;
            },
            selected: (node, coordinate) => {
              this.currentEdit = "node";
              this.currentType = "edit";
              this.showNodeFormData = this.nodeformData.filter(item=>item.name.trim()!='上级节点'&&item.name.trim()!='下级节点')
              if (0) {
                request({
                  url: "/pms/workflowMGMT/nodeList/" + node.id,
                  method: "get",
                }).then((res) => {
                  this.form = res.data;
                });
              } else {
                this.form = node.meta;
              }
            },
          },
        ],

        [
          {
            label: "属性",
            selected: (node, coordinate) => {
              this.currentEdit = "node";
              this.currentType = "show";
              this.showNodeFormData = this.nodeformData
              if (typeof node.id == "number") {
                request({
                  url: "/pms/workflowMGMT/nodeList/" + node.id,
                  method: "get",
                }).then((res) => {
                  this.form = res.data;
                });
              } else {
                this.form = node.meta;
              }
            },
          },
        ],
      ],
      linkMenuList: [
        [
          {
            label: "删除",
            disable: false,
            selected: (link, coordinate) => {
              link.remove();
            },
          },
        ],
        [
          {
            label: "编辑",
            disable: false,
            selected: (link, coordinate) => {
              this.currentEdit = "link";
                console.log(link.meta);
              this.form = link.meta;
              this.$set(
                this.form,
                "prop",
                link.meta && link.meta.prop ? link.meta.prop : "approve"
              );
              // this.form.fromName = link.start.meta.name;
              // this.form.fromDesc = link.start.meta.description;
              // this.form.toName = link._end.meta.name;
              // this.form.toDesc = link._end.meta.description;
            },
          },
        ],
      ],
      nodeformData: [],
      showNodeFormData: [],
      linkFormData: {},
      form: {},
      currentEdit: null,
      currentType: "show",
    };
  },
  created() {
    const nodeList = [];
    const linkList = [];
    this.projectid = this.$route.params.Id;
    request({
      url: "/pms/pageConfig/getAddForm?addForm=add_node",
      method: "get",
    }).then((res) => {
      this.nodeformData = res.data;
      for (let item of this.nodeformData) {
        if (item.optionValue && item.optionValue.indexOf("url") > -1) {
          let url = this.getUrl(item.optionValue.split(":")[1], {
            id: this.projectid,
          });
          request({ url: "/pms" + url, method: "get" }).then((response) => {
            if (response.code == 200) {
              item.optionValue = response.rows;
              if (response.rows && response.rows.length == 1) {
                this.form[item.prop] = response.rows[0].id;
              }
            }
          });
        }
      }
    });
    request({
      url: "/pms/"+this.$route.query.type.split('/')[1]+"/nodeFlowChartList?workflowid="+this.projectid,
      method: "get",
    }).then((Response) => {
      for (let node of Response.data.nodeList) {
        nodeList.push({
          id: node.id,
          width: 120,
          height: 60,
          coordinate: [node.x, node.y],
          meta: {
            prop:
              node.nodeName == "开始节点"
                ? "start"
                : node.nodeName == "结束节点"
                ? "end"
                : "cc",
            ...node,
          },
        });
      }
      for (let link of Response.data.workflowPath) {
        linkList.push({
          id: link.id,
          fromid: link.fromid,
          toid: link.toid,
          startAt: [120, 30],
          endAt: [0, 30],
          meta: {operationType:'Approve',...link},
        });
      }
      for(let reject of Response.data.Reject) {
        linkList.push({
          id: link.id,
          fromid: link.fromid,
          toid: link.toid,
          startAt: [120, 30],
          endAt: [0, 30],
          meta: {operationType:'Reject',...reject},
        });
      }
    });

    setTimeout(() => {
      this.nodeList = nodeList;
      this.linkList = linkList;
    }, 100);
  },
  methods: {
    enterIntercept(formNode, toNode, graph) {
      const formType = formNode.meta.prop;
      switch (toNode.meta.prop) {
        case "approval":
          return ["start", "approval", "condition", "cc"].includes(formType);
        case "condition":
          return ["start", "approval", "condition", "cc"].includes(formType);
        case "end":
          return ["approval", "cc"].includes(formType);
        default:
          return true;
      }
    },
    outputIntercept(node, graph) {
      return !(node.meta.prop === "end");
    },
    linkDesc(link) {
      return link.meta ? link.meta.desc : "";
    },
    linkStyle(link) {
      /**
       根据 link 对象的属性判断定制连线样式
      */
      return {
        color: link.meta && link.meta.operationType == "Reject" ? "#ff0000" : "#666666",
        textColor:
          link.meta && link.meta.operationType == "Reject" ? "#ff0000" : "#666666",
      };
    },
    handleSave(){
      const graph = this.$refs.superFlow.graph
      const subData = {
        nodeList: [],
        linkList: [],
        workflowId: this.projectid
      }
      for(let i of graph.nodeList){
        i.meta.x = i.position[0]
        i.meta.y = i.position[1]
        subData.nodeList.push(i.meta)
      }
      for(let j of graph.linkList){
        // console.log(j)
        j.meta.start = j.startAt.join(',')
        j.meta.end = j._endAt.join(',')
        if(!j.meta.fromid){
          j.meta.fromid = j.start.id
          j.meta.fromName = j.start.meta.nodeName
          j.meta.fromDescription = j.start.meta.description
          j.meta.toid = j._end.id
          j.meta.toName = j._end.meta.nodeName
          j.meta.toDescription = j._end.meta.description
        }
        subData.linkList.push(j.meta)
      }
      // console.log(subData)
      request({url:'/pms/workflowMGMT/flowChartAdd',method:'post',data:subData}).then(res=>{
        console.log(res)
        if(res.code==200){
          this.msgSuccess(res.msg);
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.extendedMain {
  display: block;
  line-height: 23px;
  white-space: nowrap;
  border-bottom: #d8d8d8 solid 1px;
}
.extendedMain.name {
  font-size: 16px;
  font-weight: bold;
  font-family: "3dsregular", Arial, Helvetica, sans-serif;
  max-width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.extendedMain.content {
  font-size: 13px;
  width: 300px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 5px 0 5px 10px;
}
.extendedMain.fromTitle {
  font-size: 13px;
  width: 150px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 5px 0 5px 10px;
  background-color: #f8f8f8;
}
.flex {
  display: flex;
}
.app-container {
  width: 100%;
  height: 100%;
  .formcontent {
    height: 200px;
    width: 100%;
    .formitem {
      width: 33%;
      height: 32px;
      padding: 3px 10px;
      text-align: center;
      float: left;
      box-sizing: border-box;
      .formitem-title {
        width: 50%;
        text-align: right;
        display: inline-block;
        line-height: 32px;
      }
    }
  }
  .super-flow-base-demo {
    width: 100%;
    height: calc(100% - 300px);
    // margin           : 0 auto;
    background-color: #f5f5f5;

    .super-flow__node {
      .flow-node {
        > header {
          font-size: 14px;
          height: 32px;
          line-height: 32px;
          padding: 0 12px;
          color: #ffffff;
        }

        > section {
          text-align: center;
          line-height: 20px;
          overflow: hidden;
          padding: 3px 12px;
          word-break: break-all;
          max-height: 40px;
        }

        &.flow-node-start {
          > header {
            background-color: #55abfc;
          }
        }

        &.flow-node-condition {
          > header {
            background-color: #bc1d16;
          }
        }

        &.flow-node-approval {
          > header {
            background-color: rgba(188, 181, 58, 0.76);
          }
        }

        &.flow-node-cc {
          > header {
            background-color: #30b95c;
          }
        }

        &.flow-node-end {
          > header {
            height: 60px;
            line-height: 60px;
            background-color: rgb(0, 0, 0);
          }
        }
      }
    }
  }
}
</style>
